<template>
	<view class="page__content">
		<up-navbar :fixed="false" :autoBack="true" title="SPC 控制图看板" left-icon-color="#fff" :safeAreaInsetTop="true">
		</up-navbar>

		<!-- 时间与图表选择器 -->
		<view class="filter-section">
			<u-tabs :list="chartOptionsData" :current="selectedChartIndex" @change="changeChartTab"></u-tabs>
		</view>

		<view class="page__content__main">
			<!-- 图表展示区 -->
			<view class="chart-card" v-if="selectedChartIndex == 0 && tableData.length">
				<text class="chart-title">控制图</text>
				<SpcXRChart :data="tableData" :spec="spec"></SpcXRChart>
			</view>

			<view class="chart-card" v-if="selectedChartIndex == 1 && tableData.length">
				<text class="chart-title">样本运行图</text>
				<SpcYBChart :data="tableData" :spec="spec">></SpcYBChart>

			</view>

			<view class="chart-card" v-if="selectedChartIndex == 2 && tableData.length">
				<text class="chart-title">CPK 分析图</text>
				<SpcCPKChart :data="tableData" :spec="spec"></SpcCPKChart>
			</view>

			<view class="chart-card" v-if="selectedChartIndex == 3 && tableData.length">
				<text class="chart-title">均值运行图</text>
				<SpcJZChart :data="tableData" :spec="spec"></SpcJZChart>
			</view>

			<view class="chart-card" v-if="selectedChartIndex == 4 && tableData.length">
				<text class="chart-title">正态分布图</text>
				<SpcZTChart :data="tableData"></SpcZTChart>
			</view>

			<view class="chart-card" v-if="selectedChartIndex == 5 && tableData.length">
				<text class="chart-title">合格率趋势图</text>
				<SpcHGChart :data="tableData"></SpcHGChart>
			</view>

			<zb-table :show-header="true" :columns="tableColumns" :stripe="true" :fit="false" :border="true"
				:data="tableData" height="400"></zb-table>
		</view>




	</view>
</template>

<script setup lang="ts">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore, useBluetoothStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const bluetoothStore = useBluetoothStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	import SpcXRChart from "@/st_qms/page_spc/components/ChartByXR"
	import SpcYBChart from '@/st_qms/page_spc/components/ChartByYB.vue'
	import SpcJZChart from '@/st_qms/page_spc/components/ChartByJZ.vue'
	import SpcZTChart from '@/st_qms/page_spc/components/ChartByZT.vue'
	import SpcCPKChart from '@/st_qms/page_spc/components/ChartByCPK.vue'
	import SpcHGChart from '@/st_qms/page_spc/components/ChartByHG.vue'

	let pageConfig = reactive<any>({
		LabTestProjectID: null,
		CJNum: null,
		SamplingSchemeID: null,
		ProductID: null,
	});



	let chartOptionsData = [
		{ name: '控制图' },
		{ name: '样本运行图' },
		{ name: 'CPK 分析图' },
		{ name: '均值运行图' },
		{ name: '正态分布图' },
		{ name: '合格率趋势图' },
	];

	let selectedChartIndex = ref(0)
	const changeChartTab = (item : any) => {
		setTimeout(() => {
			selectedChartIndex.value = item.index;
		}, 300);
	};

	let spec = reactive<any>({
		usl: null,
		lsl: null,
		target: null
	})

	let tableData = ref<any>([]);
	let tableColumns = ref<any>([
		{ label: '序号', name: 'index', width: 70, align: 'center' },
		{ label: '抽检时间', name: 'BillDate', width: 100 },
		{ label: '平均值', name: 'mean', width: 100 },
		{ label: '极差值', name: 'range', width: 100 },
		{ label: '标准差', name: 'stdDev', width: 100 },
		{ label: '最大值', name: 'max', width: 100 },
		{ label: '最小值', name: 'min', width: 100 },
	]);



	let filteredData = ref<any>([])
	/**
		* 计算每条记录中样本数组的统计信息，包括：
		* - 平均值（mean）
		* - 极差（range）
		* - 标准差（stdDev，样本标准差）
		* - 最大值（max）
		* - 最小值（min）
		* 
		* 保留小数位：
		* - mean：4 位
		* - range、max、min：3 位
		* - stdDev：6 位
		* 
		* 统计说明：
		* 1. mean（平均值）：
		*    mean = Σx / n
		* 
		* 2. range（极差）：
		*    range = max - min
		* 
		* 3. stdDev（样本标准差）：
		*    stdDev = sqrt( Σ(xi - mean)² / (n - 1) )
		*    说明：用 n - 1 是为了得到“样本标准差”的无偏估计
		* 
		* 4. max, min：
		*    样本的最大值、最小值
	*/
	const calculateStatsPerRecord = (data : any) => {
		return data.map((record, ind) => {
			const values = record.samples;
			const n = values.length;

			if (!Array.isArray(values) || n === 0) {
				// 无有效样本值，返回空统计字段
				return {
					...record,
					mean: null,
					range: null,
					stdDev: null,
					max: null,
					min: null
				};
			}

			// 1. 计算平均值（mean）
			const sum = values.reduce((acc, val) => acc + val, 0);
			const mean = sum / n;

			// 2. 计算最大值、最小值、极差（range）
			const max = Math.max(...values);
			const min = Math.min(...values);
			const range = max - min;

			// 3. 计算样本标准差（stdDev）
			//    方差 = Σ(xi - mean)^2 / (n - 1)
			//    标准差 = sqrt(方差)
			let variance = 0;
			if (n > 1) {
				variance = values.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / (n - 1);
			}
			const stdDev = Math.sqrt(variance);

			let ypInfo = {}
			record.samples.forEach((item, index) => {
				ypInfo['code_' + index] = item;
			})

			// 4. 返回带有统计信息的新记录

			return {
				...record,
				...ypInfo,
				index: ind + 1,
				mean: Number(mean.toFixed(4)), // 平均值保留4位小数
				range: Number(range.toFixed(3)), // 极差保留3位小数
				stdDev: Number(stdDev.toFixed(6)), // 标准差保留6位小数
				max: Number(max.toFixed(3)), // 最大值保留3位小数
				min: Number(min.toFixed(3)) // 最小值保留3位小数
			};
		});
	}

	const applyFilter = () => {
		request({
			config: {},
			url: 'Qu_LabTestProjectItemDetail',
			method: 'POST',
			data: {
				SamplingSchemeID: pageConfig.SamplingSchemeID,
				ProductID: pageConfig.ProductID,
				CJNum: pageConfig.CJNum,
				LabTestProjectID: pageConfig.LabTestProjectID,
			},
			success: async (ret : any) => {
				console.log(ret);
				if (ret.status == 200) {
					const timesMap = new Map();

					for (const item of ret.data.ds) {
						const time = item.LabTestProductItemDeID;
						if (!timesMap.has(time)) {
							timesMap.set(time, []);
						}
						timesMap.get(time).push(item);
					}

					// 将 Map 转为二维数组（按 Times 升序排列）
					const mapData = Array.from(timesMap.entries())
						.sort((a, b) => a[0] - b[0])
						.map(([_, group]) => group);

					console.log(mapData);

					let result = mapData.map(item => {
						let samples = [];
						let count = 0;
						item.forEach(row => {
							samples.push(+(row.JYJG1));
							if (row.FResult === 1) {
								count++;
							}
						});
						const ratio = (count / item.length) * 100;


						return {
							// inspectTime: '2018-08-01 10:00:00',
							BillDate: item[0].BillDate || '-',
							status: item[0]['ItemResult'] == 1 ? true : false,
							samples: samples,
							passRate: ratio
						}
					})


					let backData = calculateStatsPerRecord(result);

					if (backData.length) {

						// 插入列表字段
						if (backData[0].samples.length) {
							let columnsInfo = []
							backData[0].samples.forEach((item, index) => {
								columnsInfo.push({
									label: '样品' + (index + 1),
									name: 'code_' + index,
									width: 100
								});
							})

							tableColumns.value.splice(2, 0, ...columnsInfo);
						}
					}

					filteredData.value = JSON.parse(JSON.stringify(backData));

					console.log(backData);
					tableData.value = JSON.parse(JSON.stringify(backData));

				}

			}

		})
	}

	onLoad((option : any) => {
		if (!uni.$utils.isEmpty(option)) {
			const {
				LabTestProjectID,
				CJNum,
				SamplingSchemeID,
				ProductID,
				usl,
				lsl,
				target,
			} = option;

			Object.assign(spec, {
				usl: +usl,
				lsl: +lsl,
				target: isNaN(+target) ? null : +target
			})
			console.log(spec);

			pageConfig.LabTestProjectID = LabTestProjectID;
			pageConfig.CJNum = CJNum;
			pageConfig.SamplingSchemeID = SamplingSchemeID;
			pageConfig.ProductID = ProductID;

			applyFilter()
		}

	})
</script>

<style lang="scss">
	.page__content {
		height: 100vh;
		background-color: #f9f9f9;

		.spc-page {
			background: #f9f9f9;
			color: #333;
			padding: 20rpx;
		}

		.sticky-col {
			position: sticky;
			left: 0;
			background: #fff;
			/* 避免透明重叠 */
			z-index: 10;
		}

		.sticky-header {
			position: sticky;
			top: 0;
			/* 固定在顶部 */
			z-index: 100;
			/* 确保表头在滚动时覆盖数据行 */
			background-color: #fff;
			/* 背景色避免透明 */
		}

		.navbar {
			padding: 30rpx 20rpx;
			background: #fff;
			text-align: center;
		}

		.title {
			font-size: 36rpx;
			color: #333;
		}

		.filter-section {
			background: #fff;
			padding: 20rpx;
			border-radius: 12rpx;
			margin-bottom: 20rpx;
		}

		.time-selector {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
			margin-bottom: 20rpx;
		}

		.chart-selector {
			margin-top: 10rpx;
		}

		.time-item {
			flex: 1;
		}

		.picker-view {
			padding: 10rpx;
			background: #fff;
			color: #333;
			border-radius: 8rpx;
		}

		.btn {
			padding: 10rpx 20rpx;
			margin-top: 20rpx;
		}

		.chart-card {
			background: #fff;
			margin-bottom: 40rpx;
			padding: 20rpx;
			border-radius: 16rpx;
		}

		.chart-title {
			font-size: 28rpx;
			margin-bottom: 10rpx;
			color: #09f;
		}

		.table-container {
			margin-top: 40rpx;
			background: #fff;
			color: #333;
			border-radius: 16rpx;
			overflow: auto;
		}

		.table-row {
			display: flex;
			padding: 20rpx;
			justify-content: space-between;
			border-bottom: 1px solid #333;
		}

		.table-header {
			background: #fff;
			color: #333;
			font-weight: bold;
		}
	}
</style>